<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/2/25
 * Time: 9:39
 */
namespace app\api\job;

use think\queue\Job;
use think\Log;
use think\Db;
use think\loader;
class Jlou {

    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {

        if($data['pay_type']==2){
            //微信支付
            Loader::import('WxPay.WxPay',EXTEND_PATH,'.Api.php');
            $config = new \WxPayConfig();
            $WxPay  = new \WxPayApi();
            $WxData = new \WxPayRefund();

            $dataArr = array(

                'appid' => $config->GetAppId(),
                'mch_id' => $config->GetMerchantId(),
                'nonce_str' => $WxPay->getNonceStr(),
                'total_fee' => $data['order_price']*100,    //订单金额  单位 转为分
                'refund_fee' => $data['order_price']*100,    //退款金额 单位 转为分
                'out_trade_no'=>$data['order_sn'],    //商户订单号
                'out_refund_no'=>makeOrderSn(),    //商户退款单号
                'refund_desc'=>'参与人数不足',   //退款原因（选填）
                'notify_url'=>'http://api.lancly.com/api/Wxpays/refundNotify'
            );

            $WxData->SetAppid($dataArr['appid']);
            $WxData->SetMch_id($dataArr['mch_id']);
            $WxData->SetNonce_str($dataArr['nonce_str']);
            $WxData->SetTotal_fee($dataArr['total_fee']);
            $WxData->SetOut_trade_no($dataArr['out_trade_no']);
            $WxData->SetOut_refund_no($dataArr['out_refund_no']);
            $WxData->SetRefund_fee($dataArr['refund_fee']);
            $WxData->SetOp_user_id($dataArr['mch_id']);
            $WxData->SetNotify_url($dataArr['notify_url']);
            $WxData->SetSign($config);
            $return = $WxPay->refund($config,$WxData);
            if ($return['result_code'] == 'SUCCESS' && $return['return_code'] == 'SUCCESS'){

                echo '微信退款申请成功';
                $job->delete();
            }else{
                //任务执行超过1次，则删除任务
                if ($job->attempts() > 3) {
                    echo "执行次数超过3次";
                    $job->delete();
                }
            }
        }else if($data['pay_type']==1){
            Loader::import('Alipay.aop.AopClient');
            Loader::import('Alipay.aop.request.AlipayTradeRefundRequest');
            $aop = new \AopClient ();
            $aop->gatewayUrl = config('alipay')['gatewayUrl'];
            $aop->appId = config('alipay')['appId'];
            $aop->rsaPrivateKey =config('alipay')['rsaPrivateKey'];
            $aop->alipayrsaPublicKey=config('alipay')['alipayrsaPublicKey'];
            $aop->apiVersion = '1.0';
            $aop->signType =config('alipay')['signType'];
            $aop->postCharset='UTF-8';
            $aop->format=config('alipay')['format'];


            $request = new \AlipayTradeRefundRequest();

            $bizcontent = json_encode([ 'out_trade_no'=>$data['order_sn'],'refund_amount'=> $data['order_price'], 'refund_reason'=>'捡漏参数人数不足退款' ]);
            $request->setBizContent($bizcontent);
            $result = $aop->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $resultCode = $result->$responseNode->code;
            if($resultCode==10000 && $result->$responseNode->fund_change=='Y'){
                echo '支付宝退款成功';
                Db::name('jlou_order')->where('order_sn',$result->$responseNode->out_trade_no)->setField('is_refund',1);
                $date = [
                    'refund_sn'=>$result->$responseNode->trade_no,
                    'order_sn'=>$result->$responseNode->out_trade_no,
                    'refund_money'=>$result->$responseNode->refund_fee,
                    'refund_time'=>$result->$responseNode->gmt_refund_pay,
                    'pay_type'=>1
                ];
                Db::name('jlou_refund')->insert($date);

                $job->delete();

            }else{
                //任务执行超过1次，则删除任务
                if ($job->attempts() > 3) {
                    echo "执行次数超过3次";
                    $job->delete();
                }
            }
        }

        //任务执行超过1次，则删除任务
        if ($job->attempts() > 3) {
            echo "执行次数超过3次";
            $job->delete();
        }
        $job->delete();

    }
    /**
     * 消息在到达消费者时可能已经不需要执行了
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean 任务执行的结果
     */
    private function checkJob($data)
    {

        return true;
    }
    /**
     * 根据消息中的数据进行实际的业务处理
     */
    private function doJob($data)
    {
        //判断当前时间是否
        return true;
        // 实际业务流程处理

    }
}
